package com.ruoyi.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class WebSocketRunner implements CommandLineRunner {

    @Resource
    private WebSocketConfigdd webSocketConfigdd;
    
    @Resource
    private SystemProxyManager systemProxyManager;
    
    @Resource
    private BinanceWebSocketProxyConfig binanceWebSocketProxyConfig;

    private static final ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String, Object> getMap() {
        return map;
    }

    @Override
    public void run(String... args) {
        log.info("开始启动WebSocket连接...");
        
        // 检查是否需要代理
        if (webSocketConfigdd.needsProxyAuth()) {
            log.info("检测到代理配置，启用币安专用代理认证");
            
            // 使用币安专用代理配置
            binanceWebSocketProxyConfig.configureBinanceWebSocketProxy();
            
            // 同时启用系统代理管理器（用于其他连接）
            systemProxyManager.enableSystemProxy();
            
            // 验证代理设置
            if (systemProxyManager.testProxyConnection()) {
                log.info("代理连接测试成功");
                log.info("币安代理配置: {}", binanceWebSocketProxyConfig.getProxyInfo());
                log.info("系统代理配置: {}", systemProxyManager.getCurrentProxyInfo());
            } else {
                log.warn("代理连接测试失败，但继续尝试WebSocket连接");
            }
        } else {
            log.info("未检测到代理配置，使用直连");
        }
        
        // 使用标准WebSocketSubscriber（现在会自动使用系统代理）
        log.info("使用标准WebSocketSubscriber with Enhanced Binance Proxy");
        
        try {
            WebSocketSubscriber webSocketSubscriberKline = webSocketConfigdd.webSocketSubscriberKline();
            WebSocketSubscriber webSocketSubscriberDetail = webSocketConfigdd.webSocketSubscriberDetail();

            log.info("连接币安K线WebSocket...");
            webSocketSubscriberKline.connect();
            
            log.info("连接币安Detail WebSocket...");
            webSocketSubscriberDetail.connect();
            
            map.put("kline", webSocketSubscriberKline);
            map.put("detail", webSocketSubscriberDetail);
            map.put("clientType", "BinanceEnhancedProxy");
            map.put("proxyEnabled", systemProxyManager.isProxyEnabled());
            map.put("binanceProxyInfo", binanceWebSocketProxyConfig.getProxyInfo());
            
            log.info("WebSocket连接启动完成");
            log.info("客户端类型: BinanceEnhancedProxy");
            log.info("代理状态: {}", systemProxyManager.isProxyEnabled() ? "启用" : "禁用");
            log.info("币安代理: {}", binanceWebSocketProxyConfig.getProxyInfo());
            
        } catch (Exception e) {
            log.error("WebSocket连接启动失败", e);
            // 尝试刷新代理配置后重试
            if (webSocketConfigdd.needsProxyAuth()) {
                log.info("尝试刷新代理配置后重试...");
                binanceWebSocketProxyConfig.refreshProxyAuth();
                systemProxyManager.forceRefreshProxyConfig();
            }
        }
    }
    
    public void reStart(String... args) throws InterruptedException {
        log.info("重启WebSocket连接...");
        
        // 关闭现有连接
        WebSocketSubscriber klineClient = (WebSocketSubscriber) map.get("kline");
        WebSocketSubscriber detailClient = (WebSocketSubscriber) map.get("detail");
        
        if (klineClient != null) {
            klineClient.close();
        }
        if (detailClient != null) {
            detailClient.close();
        }
        
        // 等待连接关闭
        Thread.sleep(2000);
        
        // 刷新代理配置
        if (systemProxyManager.isProxyEnabled()) {
            log.info("刷新币安代理配置...");
            binanceWebSocketProxyConfig.refreshProxyAuth();
            systemProxyManager.refreshProxyConfig();
            
            log.info("代理配置已刷新");
            log.info("币安代理: {}", binanceWebSocketProxyConfig.getProxyInfo());
            log.info("系统代理: {}", systemProxyManager.getCurrentProxyInfo());
        }
        
        // 重新启动连接
        run(args);
    }
}
